// pages/chat/chat.ts
Page({
  data: {
    messages: [],
    inputText: '',
    loading: false,
    scrollTop: 0,
    conversationId: ''
  },

  // 输入处理
  onInput(e) {
    this.setData({ inputText: e.detail.value });
  },

  // 发送消息
  sendMessage() {
    const text = this.data.inputText.trim();
    if (!text || this.data.loading) return;

    this.addMessage(text, 'user');
    this.setData({ 
      inputText: '',
      loading: true
    });
    this.callBlockingAPI(text);
  },

  // 调用同步API
  async callBlockingAPI(query) {
    const app = getApp();
    try {
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: 'https://api.dify.ai/v1/chat-messages',
          method: 'POST',
          header: {
            'Authorization': `Bearer ${app.globalData.apiKey}`,
            'Content-Type': 'application/json'
          },
          data: {
            inputs: {},
            query,
            response_mode: "blocking", // 同步模式
            conversation_id: this.data.conversationId,
            user: app.globalData.userId
          },
          success: resolve,
          fail: reject
        });
      });

      this.handleBlockingResponse(res);
    } catch (err) {
      console.error('请求失败:', err);
      this.handleError(err);
    }
  },

  // 处理同步响应
  handleBlockingResponse(res) {
    if (res.statusCode === 200) {
      const answer = res.data.answer || '未获取到有效回答';
      this.addMessage(answer, 'assistant');
      this.setData({
        conversationId: res.data.conversation_id,
        loading: false
      });
    } else {
      throw new Error(`HTTP ${res.statusCode}: ${res.data.message}`);
    }
  },

  // 错误处理
  handleError(error) {
    console.error(error);
    this.addMessage('请求失败，请稍后重试', 'assistant');
    wx.showToast({
      title: error.message || '请求失败',
      icon: 'none',
      duration: 2000
    });
    this.setData({ loading: false });
  },

  // 添加消息
  addMessage(content, role) {
    const newMessage = {
      content,
      role,
      time: this.formatTime(new Date())
    };

    this.setData({
      messages: [...this.data.messages, newMessage],
      scrollTop: this.data.scrollTop + 10000
    });
  },

  // 时间格式化
  formatTime(date) {
    return `${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`;
  }
})